import QtQuick 2.5

Item {
    id: root
    anchors.fill: parent

    ListView {
        id: view
        width: parent.width
        height: parent.height
        anchors.bottom: btn.top
        anchors.bottomMargin: 20
        delegate: Item {
            width: root.width
            height: 100
            Image {
                id: img
                width: 80
                height: 80
                anchors.left: parent.left
                anchors.leftMargin: (parent.width / 2) - width * 2
                source: modelData.avatar
            }
            Text {
                id: name
                anchors.left: img.right
                anchors.leftMargin: 30
                anchors.top: parent.top
                anchors.topMargin: 15
                font.bold: true
                text: modelData.first_name + " " + modelData.last_name
            }
            Text {
                anchors.top: name.bottom
                anchors.topMargin: 15
                anchors.left: name.left
                color: "blue"
                text: modelData.email
            }
        }
    }

    Rectangle {
        id: btn
        width: 120
        height: 30
        color: "lightgray"
        border.color: "black"
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 20
        Text {
            anchors.centerIn: parent
            text: "Click Send Get"
        }
        MouseArea {
            id: btn_click
            anchors.fill: parent
            onClicked: {
                request("https://reqres.in/api/users");
            }
        }
    }

    function request(url) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
                print('HEADERS_RECEIVED')
            } else if (xhr.readyState === XMLHttpRequest.DONE) {
                var obj = JSON.parse(xhr.responseText.toString());
                print(obj.support.text)
                //  for (var i = 0; i < obj.data.length; ++i) {
                //    print(obj.data[i].email)
                //    print(obj.data[i].first_name)
                //  }
                // print(JSON.stringify(obj, null, 2));
                view.model = obj.data;
            }
        };
        xhr.open("GET", url);
        xhr.send();
    }

    Component.onCompleted: {
        request("https://reqres.in/api/users");
    }
}
